<?php

namespace App\Models;

use App\Exceptions\ApiException;
use App\Helpers\FileTool;
use App\User;
use Hootlex\Moderation\Moderatable;
use Illuminate\Database\Eloquent\Model;
use Overtrue\LaravelFollow\Traits\CanBeSubscribed;


class Doc extends Model
{
    use CanBeSubscribed, Moderatable;
    protected $casts = [
        'category_data' => 'array',
    ];
    protected $guarded = [];

    public function searchableAs()
    {
        return 'doc_index';
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function pages()
    {
        return $this->hasMany(DocPage::class, 'doc_id');
    }

    public function articles()
    {
        return $this->hasMany(DocArticle::class, 'doc_id');
    }

    /**
     * 获得此文章的所有标签。
     */
    public function tags()
    {
        return $this->morphToMany(Tag::class, 'taggable');
    }

    public function user_buy()
    {
        return $this->morphMany(UserBuy::class, 'item');
    }

    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }

    public function listened()
    {
        return $this->hasMany(UserListened::class, 'parent_id')->where('item_type', DocPage::class);
    }

    public function article_listened()
    {
        return $this->hasMany(UserListened::class, 'parent_id')->where('item_type', DocArticle::class);
    }

    public function last_update()
    {
        return $this->hasOne(DocPage::class, 'doc_id')->orderByDesc("updated_at");
    }

    public function last_article()
    {
        return $this->hasOne(DocArticle::class, 'doc_id')->orderByDesc("updated_at");
    }

    public static function getLastUpdatePage($doc)
    {
        $page = $doc->pages()->orderByDesc("updated_at")->first();

        return $page;
    }


    public static function getCover($doc)
    {
        $cover = $doc->cover;
        return [
            'path' => $cover,
            'cover_url' => FileTool::thumb($cover),
            'small_url' => FileTool::thumb($cover, FileTool::getImageView(300, 400)),
            'big_url' => FileTool::thumb($cover, FileTool::getImageView(600, 800)),
            'avatar_url' => FileTool::thumb($cover, FileTool::getImageView(120, 120)),
            'share_url' => FileTool::thumb($cover, FileTool::getImageView(400, 320)),
        ];
    }

    public static function getShareData($doc, $user)
    {
        $cover = $doc->cover;
        $tg_id = $user ? hashid_encode($user->id) : 0;
        return [
            'image' => FileTool::thumb($cover, FileTool::getImageView(400, 320)),
            'title' => $doc->title,
            'xcx_url' => '/pages/details/' . $doc->mode . '/main?id=' . hashid_encode($doc->id) . '&share=' . $tg_id,
            'qr_code' => urlencode(config('wx.web_host') . 'share-card?type=doc&id=' . hashid_encode($doc->id)),
        ];

    }


    public static function allCollectMenu($menus, $parent_id = 0, $source, $doc)
    {
        foreach ($menus as $v) {
            $page = DocPage::query()->create([
                'doc_id' => $doc->id,
                'title' => $v['title'],
                'content' => '',
                'is_try' => 0,
                'is_group' => 0,
                'user_id' => $doc->user_id,
                'parent_id' => $parent_id,
                'order' => $v['order'],
                'source' => $source,
                'source_key' => $v['id']
            ]);
            if (!empty($v['children'])) {
                self::allCollectMenu($v['children'], $page->id, $source, $doc);
            }
        }

    }

    /**
     * @param $doc
     * @return bool
     * @throws ApiException
     */
    public static function delDoc($doc)
    {
        //判断当前文档是否有人购买
        if ($doc->user_buy()->count() > 0) {
            throw new ApiException('文档已有订单，无法删除');
        }
        \DB::transaction(function () use ($doc) {
            $doc->delete();//删除文档主数据
            if ($doc->mode == 'docs') {
                $doc->pages()->delete();//删除文档目录数据
            }
            if ($doc->mode == 'articles') {
                $doc->articles()->delete();//删除文章数据
            }
            $doc->listened()->delete();//删除文档学习记录
            $doc->tags()->detach();//删除标签

        });

        return true;


    }

    public function getCoverAttribute($key)
    {
        $cover = "common/cover.png";

        return empty($key) ? $cover : $key;
    }


    const DOC_TYPE = [
        0 => '免费文档',
        1 => '收费文档'
    ];

}
